﻿CREATE PROCEDURE [dbo].[yaf_message_approve](
                @MessageID INT)
AS
    BEGIN
        DECLARE  @UserID INT
        DECLARE  @ForumID INT
        DECLARE  @TopicID INT
        DECLARE  @Posted DATETIME
        DECLARE  @UserName NVARCHAR(50)
        SELECT @UserID = a.UserID,
               @TopicID = a.TopicID,
               @ForumID = b.ForumID,
               @Posted = a.Posted,
               @UserName = a.UserName
        FROM   yaf_Message a,
               yaf_Topic b
        WHERE  a.MessageID = @MessageID
        AND b.TopicID = a.TopicID
        -- update yaf_Message
        UPDATE yaf_Message
        SET    Flags = Flags | 16
        WHERE  MessageID = @MessageID
        -- update yaf_User
        IF EXISTS (SELECT 1
                   FROM   yaf_Forum
                   WHERE  ForumID = @ForumID
                   AND (Flags & 4) = 0)
        BEGIN
            UPDATE yaf_User
            SET    NumPosts = NumPosts + 1
            WHERE  UserID = @UserID
            EXEC yaf_user_upgrade
                 @UserID
        END
        -- update yaf_Forum
        UPDATE yaf_Forum
        SET    LastPosted = @Posted,
               LastTopicID = @TopicID,
               LastMessageID = @MessageID,
               LastUserID = @UserID,
               LastUserName = @UserName
        WHERE  ForumID = @ForumID
        -- update yaf_Topic
        UPDATE yaf_Topic
        SET    LastPosted = @Posted,
               LastMessageID = @MessageID,
               LastUserID = @UserID,
               LastUserName = @UserName,
               NumPosts = (SELECT COUNT(1)
                           FROM   yaf_Message x
                           WHERE  x.TopicID = yaf_Topic.TopicID
                           AND (x.Flags & 24) = 16)
        WHERE  TopicID = @TopicID
        -- update forum stats
        EXEC yaf_forum_updatestats
             @ForumID
    END


